<template>
  <div>
    <crumbs :BreadCrumb="BreadCrumb"></crumbs>
    <el-row>
      <el-col>
        <el-button @click="toAddGroup" type="primary">添 加</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="groupName" label="分组名称"></el-table-column>
      <el-table-column label="适用范围">
        <template slot-scope="scope">
          <span>{{ scope.row.groupIndx | formatApplyTo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="婚姻条件">
        <template slot-scope="scope">
          <span>{{ scope.row.groupMarriage|formatMarriage }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄条件">
        <template slot-scope="scope">
          <span>{{ scope.row.groupAge|formatAge }} </span>
          <span v-if="scope.row.groupAge>0 ">{{ scope.row.ageRange }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="discountPrice"
          label="总价">
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button @click="editGroup(scope.row)" size="small" type="primary">修改</el-button>
          <el-button size="small" type="danger" @click="deletegroupinfo(scope.row)">删除</el-button>
          <el-button size="small" type="info" @click="setItems(scope.row)">体检项目</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="修改分组" :visible.sync="dialogroupedit" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm">
        <el-form-item label="分组名称" label-width="80px">
          <el-input v-model="editForm.groupName"></el-input>
        </el-form-item>
        <el-form-item label="适用范围" label-width="80px">
          <el-select v-model="editForm.groupIndx" style="width: 100%">
            <el-option v-for="(item,index) in optionsSex" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="婚姻分组" label-width="80px">
          <el-select v-model="editForm.groupMarriage" style="width: 100%">
            <el-option v-for="(item,index) in optionsMarriage" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄分组" label-width="80px">
          <el-select v-model="editForm.groupAge" @change="getage" style="width: 100%">
            <el-option v-for="(item,index) in groupAge" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄限制" v-show="ageRange" label-width="80px">
          <el-input v-model="editForm.ageRange"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editgroupinfo">确 定</el-button>
        <el-button @click="dialogroupedit = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="体检项目"
        width="90%"
        :visible.sync="itemsDialog"
        class="top_dialog"
        destroy-on-close
    >
      <el-row :gutter="20" class="bg-grey">
        <el-col :span="11">
          <div class="tableTitle">
            <el-form
                :inline="true"
                :model="examItemSearchForm"
                class="demo-form-inline"
            >
              <el-form-item>
                <el-input
                    v-model="examItemSearchForm.itemName"
                    placeholder="项目名称"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="queryExamItemList">查找</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!-- :key="tableKey" -->
          <div class="bg-blue">
            <!-- :key="tableKey" -->
            <el-table
                ref="staffTable"
                :data="staffList"
                max-height="500"
                :row-key="getRowKey"
                border
                fit
                highlight-current-row
                @selection-change="handleStaffChange"
            >
              <el-table-column type="selection" :reserve-selection="true" width="55" align="center">
              </el-table-column>
              <el-table-column label="科室名称" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.deptName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="项目名称" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.itemName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="价格" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.price }}</span>
                </template>
              </el-table-column>

              <el-table-column label="适用范围" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.applyTo|formatApplyTo }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col :span="2" align="center" class="buttonAll" style="padding-top: 140px;">
          <el-button @click="addStaff('single')" type="primary" :disabled="!staffData.length" class="staffButton">
            <i class="el-icon-arrow-right"></i>
            <i class="el-icon-arrow-right"></i>
          </el-button>
          <br>
          <el-button
              @click="removeStaff('single')"
              type="primary"
              :disabled="!selectedStaffData.length"
              class="staffButton"
              style="margin-top: 25px"
          >
            <i class="el-icon-arrow-left"></i>
            <i class="el-icon-arrow-left"></i>
          </el-button>
        </el-col>
        <el-col :span="11">
          <div class="tableTitle pb-20">
            当前体检项目列表（{{ selectedLength }}项）
            <!-- <el-checkbox v-model="nsmAll" @change="toggleSelection(newmeidcal)" class="mar-10">全选/不选</el-checkbox> -->
            <div class="nsm-right-top">
              <el-button type="primary" @click="setmeal">选择体检套餐</el-button>
            </div>
          </div>
          <div class="bg-blue">
            <el-table
                ref="selectedStaffTable"
                :data="selectedStaffList"
                max-height="500"
                :row-key="getRowKey"
                border
                fit
                highlight-current-row
                @selection-change="handleSelectedStaffChange"
            >
              <el-table-column type="selection" :reserve-selection="true" width="55" align="center"></el-table-column>
              <el-table-column prop="itemName" label="项目名称" align="center">
              </el-table-column>
              <el-table-column prop="price" label="价格" align="center">
              </el-table-column>
              <el-table-column label="适用范围" align="center">
                <template slot-scope="{ row }">
                  <span>{{ row.applyTo|formatApplyTo }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-row style="margin-top: 15px">
            <el-col :span="12">分组名称: {{ groupCur.groupName }}</el-col>
            <el-col :span="12" style="text-align: right;">金额合计:<span
                style="font-size: 200%;color: #f00;border: 1px solid #000;padding: 4px 10px;">{{ originalprice }}</span>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row style="margin-top: 30px;" type="flex" align="middle">
        <el-col :span="24" style="text-align: right;padding-bottom: 20px;">
          <el-button type="primary" @click="sendtotal">保存</el-button>
          <el-button @click="itemsDialog=false">取 消</el-button>
        </el-col>
      </el-row>
<!--      <groupItems :show="itemsDialog" :group="groupCur" actionType="submit" @change="itemsChange"/>-->
    </el-dialog>

    <!-- 选择套餐 -->
    <el-dialog
        title="选择套餐"
        :visible.sync="dialogPackage"
        width="70%"
        class="top_dialog"
        append-to-body
    >
      <el-form :inline="true" :model="packageSearchForm" class="demo-form-inline">
        <el-form-item label="">
          <el-input
              v-model="packageSearchForm.packageName"
              placeholder="输入查询关键词"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="readPackageList">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
          ref="multipleTable1"
          :data="packageList"
          tooltip-effect="dark"
          border
          style="width: 100%"
          max-height="500"
          @select="selectPackage"
      >
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="packageCode" label="套餐编号"></el-table-column>
        <el-table-column prop="packageName" label="套餐名称"></el-table-column>
        <el-table-column prop="code" label="代码" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="packageType" label="体检类型" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="applyTo" label="适用范围" width="80">
          <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="80">
        </el-table-column>
        <el-table-column prop="unitName" label="单位名称" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savemealis">确定
        </el-button>
        <el-button @click="dialogPackage = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crumbs from "@src/views/Crumbs";
import groupItems from "../common/groupItems.vue";
import {optionsSex, optionsMarriage, groupAge, contractStatus} from "@src/common/utils/constant";


export default {
  components: {
    crumbs,
    groupItems,
  },
  name: "contractGroup",
  data() {
    return {
      BreadCrumb: [
        {path: "", name: "基础管理"},
        {path: "/basic/contractGroup", name: "团检分组"},
      ],
      optionsSex: optionsSex,
      optionsMarriage: optionsMarriage,
      groupAge: groupAge,
      groupId: null,
      editForm: {},
      ageRange: false,
      dialogroupedit: false,
      itemsDialog: false,
      groupCur: {
        selectedList:[]
      },
      tableData: [],
      total: 0,
      pageSize: 10,
      pageNo: 1,

      examItemSearchForm: {},
      packageSearchForm: {},
      packageSel: {
        packageName:"",
        price:0,
      },
      staffList: [],
      staffListInit: [],
      staffData: [],
      selectedStaffData: [],
      selectedStaffList:  [],
      selectedStaffListInit:  [],
      selectedLength:0,
      packageList: [],
      originalprice: 0,
      dialogPackage: false,
      dialogItems: this.show,
      groupData: this.group,
      action: this.actionType,
      res:{}
    }
  },
  filters: {
    formatContractStatus: function (val) {
      const dict = {}
      contractStatus.forEach(v => {
        dict[v.value] = v.label
      })
      return dict[val]
    },
    formatDate: function (time) {
      if (time != null && time !== "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
      } else {
        return "";
      }
    },
    formatApplyTo: function (val) {
      const dict = {}
      optionsSex.forEach(v => {
        dict[v.value] = v.label
      })
      return dict[val]
    },
    formatMarriage: function (val) {
      const dict = {}
      optionsMarriage.forEach(v => {
        dict[v.value] = v.label
      })
      return dict[val]
    },
    formatAge: function (val) {
      const dict = {}
      groupAge.forEach(v => {
        dict[v.value] = v.label
      })
      return dict[val]
    },
    formatSex: function (val) {
      var dict = {1: "男", 2: "女"}
      return dict[val]
    },
    formatType: function (val) {
      var dict = {1: "普通体检", 2: "单位体检", 3: "入职体检", 4: "职业体检", 5: "婚育体检", 6: "老年专项体检", 7: "健康体检等"}
      return dict[val]
    },
    formatStatus: function (val) {
      var dict = {1: "未登记", 2: "登记", 4: "检中", 8: "交表", 16: "初检", 32: "复检", 64: "打印"}
      return dict[val]
    },
  },
  methods: {
    queryGroupList() {
      this.$axios.selectGroupTemplateList({
        ...this.editForm
      }).then(res => {
        if (res.code === '00000') {
          this.tableData = res.data
          this.total = res.data.length
        }
      })
    },
    toAddGroup() {
      this.dialogroupedit = true
      this.editForm = {}
      this.ageRange=false
    },
    itemsChange(e) {
      const {show} = e
      this.itemsDialog = show
    },
    // 根据分组查询体检项目
    examItemList(params) {
      this.$axios.examItemList(
          params
      ).then(res => {
        if (res.code == '00000') {
          this.staffList = res.data.records
        }
      })
    },

    // 编辑合同分组
    editGroup(row) {
      this.groupId=row.id
      this.dialogroupedit = true
      this.editForm = Object.assign({}, row);  //表格给form传值
      this.ageRange = row.ageRange>0
    },
    // 编辑合同分组
    editgroupinfo() {
      if (this.groupId === null) {
        this.$axios.insertGroupTemplateList(this.editForm).then(res => {
          if (res.code === '00000') {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.queryGroupList();
          }
        })
      } else {
        this.$axios.updateGroupTemplateList({
          ...this.editForm
        }).then(res => {
          if (res.code === '00000') {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.queryGroupList();
          }
        })
      }

      this.dialogroupedit = false;
    },
    // 删除合同分组
    deletegroupinfo(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.deleteGroupTemplateList({
          id: row.id
        }).then(res => {
          console.log(res)
          if (res.code === '00000') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryGroupList(row.contractId);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 年龄限制
    getage() {
      if (this.editForm.groupAge == 0) {
        this.editForm.ageRange = null
        this.ageRange = false
      } else {
        this.ageRange = true
      }
    },


    setItems(row) {
      this.itemsDialog = true;
      this.groupCur = row;
      this.packageSearchForm.applyTo = row.groupIndx
      this.queryExamItemList()
      this.getGroupItems()
    },
    queryExamItemList() {
      const params = {...this.examItemSearchForm,pageNo:1,pageSize:999999999}
      this.$axios.examItemList(params).then(res => {
        if (res.code === '00000') {
          const {records} = res.data

          this.staffListInit = records.slice()
          this.staffList = records
        }
      })
    },
    // 已保存项目明细
    getGroupItems() {
      this.$axios.getGroupTemplateInfo({
        id: this.groupCur.id
      }).then(res => {
        if (res.code === '00000') {
          const {peContractsGroupItemTemplates} = res.data
          this.selectedStaffListInit = peContractsGroupItemTemplates.slice()
          this.selectedStaffList = peContractsGroupItemTemplates
          this.getSummaries();
        }
      })
    },
    handleStaffChange(rows) {
      this.staffCheckNum = rows.length
      this.staffData = rows
    },

    getRowKey(row) {
      return row.itemId
    },
    // 左->右(单选-全选)
    addStaff(type) {
      setTimeout(() => {
        // 清空选择
        this.$refs['staffTable'].clearSelection()
        this.$refs['selectedStaffTable'].clearSelection()
      }, 0)
      if (type === 'single') {
        this.staffData.forEach((item) => {
          this.selectedStaffList.push(item)
        })
        this.selectedStaffNum = this.selectedStaffList.length
        for (let i = 0; i < this.staffList.length; i++) {
          for (let j = 0; j < this.staffData.length; j++) {
            if (this.staffList[i].id === this.staffData[j].id) {
              this.staffList.splice(i, 1)
              this.staffNum = this.staffList.length
            }
          }
        }
      }
      this.getSummaries();
    },
    // 右边表格选中存入selectedStaffData
    handleSelectedStaffChange(rows) {
      this.selectedStaffCheckNum = rows.length
      this.selectedStaffData = []
      if (rows) {
        rows.forEach((row) => {
          if (row) {
            this.selectedStaffData.push(row)
          }
        })
      }
    },
    // 右->左(单选-全选)
    removeStaff(type) {
      setTimeout(() => {
        this.$refs['staffTable'].clearSelection()
        this.$refs['selectedStaffTable'].clearSelection()
      }, 0)
      if (type === 'single') {
        this.selectedStaffData.forEach((item) => {
          this.staffList.push(item)
          this.staffNum = this.staffList.length
        })
        // console.log('this.staffList', this.staffList)
        for (let i = 0; i < this.selectedStaffList.length; i++) {
          for (let j = 0; j < this.selectedStaffData.length; j++) {
            if (
                this.selectedStaffList[i] &&
                this.selectedStaffData[j] &&
                this.selectedStaffList[i].id === this.selectedStaffData[j].id
            ) {
              this.selectedStaffList.splice(i, 1)
              this.selectedStaffNum = this.selectedStaffList.length
            }
          }
        }
      }
      if (type === 'all') {
        this.selectedStaffList.forEach((item) => {
          this.staffList.push(item)
          this.staffNum = this.staffList.length
        })
        this.selectedStaffList = []
        this.selectedStaffNum = 0
      }
      this.getSummaries();
    },
    // 合计方法
    getSummaries() {
      let totalPrice = 0.00
      this.selectedStaffList.forEach((item) => {
        if (item.price == null) {
          item.price = 0;
          totalPrice += parseFloat(item.price);
        } else {
          totalPrice += parseFloat(item.price);
        }
      });
      this.originalprice = totalPrice.toFixed(2)
    },
    // 选择套餐
    setmeal() {
      this.dialogPackage = true;
      this.readPackageList();  //这里改成根据分组id获取套餐
    },
    readPackageList() {
      const params = {...this.packageSearchForm ,pageNo:1,pageSize:999999999}
      this.$axios.queryPbPackagesList(params).then(res => {
        if (res.code === '00000') {
          this.packageList = res.data.records
        }
      })
    },

    selectPackage(selection, row) {
      this.packageSel = row;
      if (selection.length > 1) {
        let del_row = selection.shift()
        this.$refs.multipleTable1.toggleRowSelection(del_row, false) // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      }
    },
    // 储存选择的套餐
    savemealis() {
      this.$axios.queryPackagItems({
        "packageId": this.packageSel.id, pageNo:1, pageSize:999999999
      }).then(res => {
        if (res.code === '00000') {
          let arr = res.data.examItemsDTOList;
          if (this.selectedStaffList.length === 0) {
            this.selectedStaffList = arr
          } else {
            this.selectedStaffList = this.selectedStaffList.concat(arr);
          }
          this.selectedStaffList.map(v => {
            return {
              ...v,
              postType: "单位",
              payStatus: 1,
            }
          })
          this.getSummaries()
        }
      })

      this.dialogPackage = false;
    },
    sendtotal() {
      let items = []
      if(this.selectedStaffList.length===0){
        this.$message.error("请添加体检项目")
        return
      }
      this.selectedStaffList.forEach(item => {
        if (item.id != null) {
          items.push(
              {
                "applyTo": item.applyTo,
                "groupId": item.groupId,
                "itemId": item.itemId||item.id,
                "price": item.price,
                "itemName": item.itemName,
                // "sequence": "显示序号"
              }
          )
        }
      })
      let obj = {
        "id": this.groupCur.id,
        "packageName": this.packageSel.packageName,
        "packagePrice": this.packageSel.price,
        "discountPrice": this.originalprice,
        "peContractsGroupItemTemplates": items
      }

      this.$axios.updateGroupTemplateList(obj).then(res => {
        if (res.code === '00000') {
          this.$message.success("提交成功")
          this.itemsDialog = false
        }
      })
    },

  },
  created() {
    this.queryGroupList()
  }
}
</script>

<style scoped>

</style>
